﻿using System;
using System.ComponentModel;
using System.Reflection;
using System.Resources;

namespace Lukianol.ComponentModel
{
    /// <summary>
    /// Get a display name from a resource manager by a name 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class ResxDisplayNameAttribute : DisplayNameAttribute
    {
        private const string ResourceManagerPropertyName = "ResourceManager";
        private readonly string _name;
        private readonly Type _resourceManagerProvider;
        private string _displayName;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name">The name of a string resource</param>
        /// <param name="resourceManagerProvider">The type of a class generated by *ResXFileCodeGenerator custom tool </param>
        public ResxDisplayNameAttribute(string name, Type resourceManagerProvider)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (resourceManagerProvider == null) throw new ArgumentNullException("resourceManagerProvider");

            _name = name;
            _resourceManagerProvider = resourceManagerProvider;
        }

        public override string DisplayName
        {
            get
            {
                if (_displayName == null)
                {
                    var propertyInfo = _resourceManagerProvider.GetProperty(ResourceManagerPropertyName, BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
                    _displayName = ((ResourceManager) propertyInfo.GetValue(null, null)).GetString(_name);
                }

                return _displayName;
            }
        }
    }
}